import { useModel } from 'umi';
import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import CreateParkingspot from './components/CreateParkingspot';
import UpdateParkingspot from './components/UpdateParkingspot';
import {
  deleteMulSpots,
  queryParkinglotNames,
  queryParkingspots,
  removeParkingspot,
} from './service';
import type { SpotTableItem } from './types.d';
import { queryCompanies } from '@/pages/SystemUser/service';
import ExportModal from './components/ExportModal';
import { Button, message, notification, Table, Modal } from 'antd';
import { useRef } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;
export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.parkingspot || []) : new Set();
  const ifCreate = auths.has(Auths.CREATE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifDelete = auths.has(Auths.DELETE);
  const ifExport = auths.has(Auths.EXPORT);
  const ref = useRef<ActionType>();
  const columns: ProColumns<SpotTableItem>[] = [
    {
      title: 'id',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: '_id',
    },
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      width: 120,
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      render: (_, record) => record.ownerInfo?.ownerName,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
    },
    {
      title: '路段名称',
      dataIndex: 'parkingLotId',
      width: 120,
      hideInForm: true,
      align: 'center',
      render: (_, record) => record.parkingLotName,
      fieldProps: { showSearch: true },
      debounceTime: 300,
      request: (val) => queryParkinglotNames(val.keyWords),
    },
    {
      title: '泊位编号',
      width: 120,
      align: 'center',
      dataIndex: 'parkingSpotId',
      hideInForm: true,
    },
    {
      title: '地磁编号',
      width: 120,
      dataIndex: 'deviceSn',
      hideInForm: true,
      align: 'center',
      render: (_, record) => (record.deviceSn ? record.deviceSn : '未绑定设备'),
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      width: 120,
      hideInForm: true,
      align: 'center',
      valueEnum: {
        99: { text: '未知状态', status: 'Default' },
        0: { text: '空闲', status: 'Success' },
        1: { text: '车牌未录入', status: 'Error' },
        2: { text: '车牌待录入', status: 'Processing' },
        3: { text: '车牌已录入', status: 'Processing' },
      },
    },
    {
      title: '当前车牌',
      dataIndex: 'licensePlate',
      width: 120,
      hideInForm: true,
      align: 'center',
    },
    {
      title: '创建时间',
      width: 240,
      dataIndex: 'createTime',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      width: 150,
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      hideInSearch: true,
      render: (_, record, x, action) =>
        ifModify || ifDelete
          ? [
              ifModify && (
                <UpdateParkingspot parkingspotData={record} func={() => action?.reload()} />
              ),
              ifDelete && (
                <ConfirmModal
                  reload={() => action?.reload()}
                  operFunc={async () => await removeParkingspot(record._id)}
                  text={`确认要删除 ${record.parkingLotName} 的 ${record.parkingSpotId} 泊位？`}
                />
              ),
            ]
          : [<PlaceHolderCpn key={record._id} />],
    },
  ];
  const openNotification = (msg: string = '删除失败') => {
    const key = `open${Date.now()}`;
    const btn = (
      <Button type="primary" size="small" onClick={() => notification.close(key)}>
        已读
      </Button>
    );
    notification.open({
      message: '泊位批量删除失败',
      description: msg,
      btn: btn,
      duration: null,
      key,
    });
  };
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle:
          '现场测绘的泊位数据会在此处展示，如果您已知泊位具体经纬度数据，也可以手动创建泊位',
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            { path: '/parkingspot', breadcrumbName: '泊位管理' },
          ],
        },
      }}
    >
      <ProTable<SpotTableItem>
        columns={columns}
        rowKey="_id"
        columnEmptyText="暂无数据"
        scroll={{ x: true }}
        search={{
          labelWidth: 'auto',
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL],
        }}
        actionRef={ref}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <span>
            已选 {selectedRowKeys.length} 项
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </span>
        )}
        tableAlertOptionRender={({ selectedRowKeys }) => {
          return ifDelete ? (
            <a
              onClick={async () => {
                if (selectedRowKeys.length <= 0) {
                  message.warn({ content: '请选择需要删除的泊位', key: 'mul-remove' });
                  return false;
                }
                confirm({
                  title: '删除确认',
                  icon: <ExclamationCircleOutlined />,
                  content: '是否确认删除当前所选项',
                  onOk: async () => {
                    const res = await deleteMulSpots(selectedRowKeys as string[]);
                    ref.current?.reload();
                    if (res?.success) {
                      message.success({ content: '删除成功', key: 'mul-remove' });
                      return true;
                    }
                    openNotification(res?.message);
                    return false;
                  },
                });
                return false;
              }}
            >
              批量删除
            </a>
          ) : (
            <PlaceHolderCpn />
          );
        }}
        style={{ whiteSpace: 'nowrap' }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
          onChange: () => {
            if (ref?.current?.clearSelected) ref?.current?.clearSelected();
          },
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryParkingspots(param, sort);
          return res;
        }}
        toolBarRender={(action) => [
          ifCreate && <CreateParkingspot func={() => action?.reload()} />,
          ifExport && <ExportModal />,
        ]}
      />
    </PageHeaderWrapper>
  );
};
